package com.future.mayi.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.dialog.CommonDialog;
import com.future.mayi.dialog.ConfirmGoodsDialog;
import com.future.mayi.model.AppraisalGoodsItemModel;
import com.future.mayi.model.AppraisalOrderModel;
import com.future.mayi.model.SellerAddressModel;
import com.future.mayi.model.interfaces.DialogEnterListener;
import com.future.mayi.response.AppraisalOrderInfoResponse;
import com.future.mayi.response.SellerAddressResponse;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.KefuUtils;
import com.future.mayi.utils.Navigator;
import com.future.mayi.utils.PriceUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 鉴定、养护订单
 */
public class AppraisalOrderActivity extends BaseTitleActivity {


    @BindView(R.id.tv_express_company)
    TextView tvExpressCompany;
    @BindView(R.id.tv_express_find)
    TextView tvExpressFind;
    @BindView(R.id.tv_express_code)
    TextView tvExpressCode;
    @BindView(R.id.ll_express)
    LinearLayout llExpress;
    @BindView(R.id.tv_refund_state)
    TextView tvRefundState;
    @BindView(R.id.tv_refund_info)
    TextView tvRefundInfo;
    @BindView(R.id.tv_refund_content)
    TextView tvRefundContent;
    @BindView(R.id.ll_refund)
    LinearLayout llRefund;
    @BindView(R.id.title_view_line)
    View titleViewLine;
    @BindView(R.id.tv_sub_title)
    TextView tvSubTitle;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.tv_jijian_name)
    TextView tvJijianName;
    @BindView(R.id.tv_jijian_phone)
    TextView tvJijianPhone;
    @BindView(R.id.tv_jijian_address)
    TextView tvJijianAddress;
    @BindView(R.id.tv_huiji_name)
    TextView tvHuijiName;
    @BindView(R.id.tv_huiji_phone)
    TextView tvHuijiPhone;
    @BindView(R.id.tv_huiji_address)
    TextView tvHuijiAddress;
    @BindView(R.id.tv_all_price)
    TextView tvAllPrice;
    @BindView(R.id.tv_red_packet_price)
    TextView tvRedPacketPrice;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.ll_server)
    LinearLayout llServer;
    @BindView(R.id.tv_order_code)
    TextView tvOrderCode;
    @BindView(R.id.ll_order_code_copy)
    LinearLayout llOrderCodeCopy;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_order_state)
    TextView tvOrderState;
    @BindView(R.id.tv_enter)
    TextView tvEnter;
    @BindView(R.id.ll_results)
    View llResults;
    @BindView(R.id.ll_results_img)
    LinearLayout llResultsImg;
    @BindView(R.id.view_red_packet)
    View viewRedPacket;
    @BindView(R.id.rl_red_packet)
    RelativeLayout rlRedPacket;

    private String orderId;
    private AppraisalOrderModel model;
    private LayoutInflater mInflater;

    private boolean backMain = false;
    private int style = 0;

    public static void startActivity(Context context, String orderId, int style) {
    }

    public static void startActivity(Context context, String orderId, int style, boolean backMain) {
    }

    public static void startActivity(Context context, AppraisalOrderModel model, int style) {
    }

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("待付款");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_appraisal_order);
    }

    @Override
    protected void initView() {
        mInflater = LayoutInflater.from(this);
    }

    @Override
    protected void initDates() {
        orderId = getIntent().getStringExtra("orderId");
        backMain = getIntent().getBooleanExtra("backMain", false);
        style = getIntent().getIntExtra("style", 1);
        if (getIntent().getSerializableExtra("model") != null)
            model = (AppraisalOrderModel) getIntent().getSerializableExtra("model");
        if (model != null) {
            orderId = String.valueOf(model.getOrder_id());
        }
        setView();
        refreshSellerAddress();

    }

    @Override
    protected void initListener() {
        getRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (model == null) return;
                if (model.getStatus() == 0) {
                    //取消订单
                    new CommonDialog.Builder(AppraisalOrderActivity.this)
                            .setCancelable(false)
                            .setMessage("确定取消该订单吗？")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    confirmOrCancel(90);
                                }
                            }).show();
                } else if (model.getStatus() == 50) {
                    //撤销退款
                    new CommonDialog.Builder(AppraisalOrderActivity.this)
                            .setCancelable(false)
                            .setMessage("确认取消本次退款申请吗？")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    cancelRefund();
                                }
                            }).show();
                } else if (model.getStatus() == 10) {
                    //申请退款
                }
            }
        });
    }


    @OnClick({R.id.tv_express_find, R.id.tv_refund_info, R.id.ll_server, R.id.ll_order_code_copy, R.id.tv_enter, R.id.rl_jishou, R.id.rl_recycle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_express_find:
                CourierInfoActivity.startActivity(this, String.valueOf(model.getOrder_id()), true, (TextUtils.isEmpty(model.getExpress_no()) ? 0 : 1));
                break;
            case R.id.tv_refund_info:
                break;
            case R.id.ll_server:
                KefuUtils.startActivity(this);
                break;
            case R.id.ll_order_code_copy:
                llOrderCodeCopy.setEnabled(false);
                CommonUtils.clipData(this, model.getOrder_no());
                toast("复制成功");
                llOrderCodeCopy.setEnabled(true);
                break;
            case R.id.tv_enter:
                tvEnter.setEnabled(false);
                enter();
                tvEnter.setEnabled(true);
                break;
            case R.id.rl_jishou:
                Navigator.navigatorToConsignSaleActivity(this);
                break;
            case R.id.rl_recycle:
                Navigator.navigatorToRecycleActivity(this);
                break;
        }
    }

    private void enter() {
        switch (model.getStatus()) {
            // 0-待付款
            case 0:
                break;
            // 10-待寄件
            case 10:
                //填写寄件
                EdtExpressActivity.startActivity(this, orderId);
                break;
            // 20-待收货
            case 20:
                confirm();
                break;
            // 30-待评价
            case 30:
                EvaluationActivity.startActivity(this, orderId, true);
                break;
            default:
                break;
        }

    }

    private void setView() {
        if (model == null) return;
        TextView tvTitle = getTitleText();
        TextView tvRight = getRightText();
        tvRight.setVisibility(View.GONE);
        llRefund.setVisibility(View.GONE);
        llExpress.setVisibility(View.GONE);
        switch (model.getStatus()) {
            // 0-待付款
            case 0:
                tvEnter.setVisibility(View.VISIBLE);
                setText(tvEnter, "立即支付");
                setText(tvTitle, "待付款");
                setText(tvOrderState, "待付款");
                tvRight.setVisibility(View.VISIBLE);
                setText(tvRight, "取消订单");
                break;
            // 10-待寄件
            case 10:
                tvEnter.setVisibility(View.VISIBLE);
                setText(tvEnter, "填写寄件");
                setText(tvTitle, "待寄件");
                setText(tvOrderState, "待寄件");
                tvRight.setVisibility(View.VISIBLE);
                setText(tvRight, "申请退款");
                break;
            // 待养护/鉴定
            case 11:
                tvEnter.setVisibility(View.GONE);
                setText(tvTitle, "待".concat(style == 1 ? "鉴定" : "养护"));
                setText(tvOrderState, "待".concat(style == 1 ? "鉴定" : "养护"));
                setLlExpress();
                break;
            // 20-待收货
            case 20:
                tvEnter.setVisibility(View.VISIBLE);
                setText(tvEnter, "确认收货");
                setLlExpress();
                setText(tvTitle, "待收货");
                setText(tvOrderState, "待收货");
                break;
            // 30-待评价
            case 30:
                tvEnter.setVisibility(View.VISIBLE);
                setText(tvEnter, "立即评价");
                setLlExpress();
                setText(tvTitle, "待评价");
                setText(tvOrderState, "待评价");
                break;
            // 40-已完成
            case 40:
                tvEnter.setVisibility(View.GONE);
                setText(tvTitle, "已完成");
                setText(tvOrderState, "已完成");
                getRightText().setVisibility(View.GONE);
                break;
            // 50-退款申请中
            case 50:
                tvEnter.setVisibility(View.GONE);
                setText(tvTitle, "退款审核中");
                setText(tvOrderState, "退款审核中");
                setText(tvRefundState, "退款审核中");
                setText(tvRefundContent, "商家将会及时和您联系退款事宜");
                llRefund.setVisibility(View.VISIBLE);
                tvRight.setVisibility(View.VISIBLE);
                setText(tvRight, "取消退款");
                break;
            // 51-退款已拒绝
//            case 51:
//                tvEnter.setVisibility(View.GONE);
//                setText(tvTitle, "退款被拒绝");
//                setText(tvOrderState, "退款被拒绝");
//                setText(tvRefundState, "退款被拒绝");
//                setText(tvRefundContent, "商家将会及时和您联系退款事宜");
//                llRefund.setVisibility(View.VISIBLE);
//                break;
            // 60 -退款成功
            case 60:
                tvEnter.setVisibility(View.GONE);
                setText(tvTitle, "退款成功");
                setText(tvOrderState, "退款成功");
                setText(tvRefundState, "退款成功");
                setText(tvRefundContent, "退款金额已经原路返回到您的支付账户");
                llRefund.setVisibility(View.VISIBLE);
                break;
            // 90-已取消
            case 90:
                tvEnter.setVisibility(View.GONE);
                setText(tvTitle, "已取消");
                setText(tvOrderState, "已取消");
                break;
        }

        setText(tvHuijiName, model.getAddress_user());
        setText(tvHuijiPhone, model.getAddress_tel());
        setText(tvHuijiAddress, model.getAddress());


        llGoods.removeAllViews();
        if (model.getGoods_item() != null && model.getGoods_item().size() > 0) {
            View viewLine = null;
            for (AppraisalGoodsItemModel model : model.getGoods_item()) {
                View view = mInflater.inflate(R.layout.layout_appraisal_goods_item, llGoods, false);
                ImageView ivImg = (ImageView) view.findViewById(R.id.iv_img);
                TextView tvGoodsPrice = (TextView) view.findViewById(R.id.tv_goods_price);
                TextView tvGoodsNum = (TextView) view.findViewById(R.id.tv_goods_num);
                TextView tvGoodsTitle = (TextView) view.findViewById(R.id.tv_title);
                view.findViewById(R.id.tv_goods_price_y).setVisibility(View.INVISIBLE);
                tvGoodsPrice.setVisibility(View.INVISIBLE);
                viewLine = view.findViewById(R.id.view_line);
                HCUtils.loadWebImg(this, ivImg, model.getCate_img());
                tvGoodsTitle.setText(model.getGoods_name());
                tvGoodsPrice.setText(PriceUtils.getPriceText2(model.getUnit_price()));
                tvGoodsNum.setText((String.valueOf(model.getBuy_num())));
                view.setTag(model);
                view.setOnClickListener(this);
                llGoods.addView(view);
            }
            if (viewLine != null) viewLine.setVisibility(View.GONE);
        }

        setText(tvAllPrice, "¥ ".concat(PriceUtils.getPriceText2(model.getAll_total_price())));

        if (model.getRedpack_discount() > 0) {
            viewRedPacket.setVisibility(View.VISIBLE);
            rlRedPacket.setVisibility(View.VISIBLE);
            setText(tvRedPacketPrice, "-¥ ".concat(PriceUtils.getPriceText2(model.getRedpack_discount())));
        } else {
            viewRedPacket.setVisibility(View.GONE);
            rlRedPacket.setVisibility(View.GONE);
        }
        setText(tvPrice, "¥ ".concat(PriceUtils.getPriceText2(model.getPay_price())));
        setText(tvOrderCode, "订单编号：".concat(model.getOrder_no() == null ? "" : model.getOrder_no()));
        setText(tvOrderTime, model.getCreatetime());


        if (style == 1 && (model.getStatus() == 20 || model.getStatus() == 30 || model.getStatus() == 40) && model.getGoods_item() != null && model.getGoods_item().size() > 0) {
            llResults.setVisibility(View.VISIBLE);
            llResultsImg.removeAllViews();
            for (int i = 0; i < model.getGoods_item().size(); i++) {
                AppraisalGoodsItemModel appraisalGoodsItemModel = model.getGoods_item().get(i);
                if (appraisalGoodsItemModel == null || appraisalGoodsItemModel.getResult_img() == null)
                    continue;
                ImageView imageView = new ImageView(this);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(CommonUtils.dip2px(this, 100), CommonUtils.dip2px(this, 100));
                layoutParams.leftMargin = CommonUtils.dip2px(mContext, 10);
                layoutParams.rightMargin = CommonUtils.dip2px(mContext, 10);
                imageView.setLayoutParams(layoutParams);
                llResultsImg.addView(imageView);
                imageView.setTag(R.id.img_result_tag, i);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, PhotoActivity.class);
                        ArrayList<String> list = new ArrayList<>();
                        for (AppraisalGoodsItemModel models : model.getGoods_item()) {
                            if (models != null && models.getResult_img() != null)
                                list.add(models.getResult_img());
                        }
                        intent.putExtra("listUrl", list);
                        intent.putExtra("setCurrentItem", (int) v.getTag(R.id.img_result_tag));
                        mContext.startActivity(intent);
                    }
                });
                HCUtils.loadWebImg(this, imageView, appraisalGoodsItemModel.getResult_img());
            }
            findViewById(R.id.iv_result_more).setVisibility(llResultsImg.getChildCount() > 2 ? View.VISIBLE : View.INVISIBLE);
        } else llResults.setVisibility(View.GONE);

    }

    /**
     * 设置物流
     */
    public void setLlExpress() {
        llExpress.setVisibility(View.VISIBLE);
        if (TextUtils.isEmpty(model.getExpress_no())) {
            setText(tvExpressCompany, "物流公司：" + model.getJj_express_name());
            setText(tvExpressCode, "物流单号：" + model.getJj_express_no());
        } else {
            setText(tvExpressCompany, "物流公司：" + model.getExpress_name());
            setText(tvExpressCode, "物流单号：" + model.getExpress_no());
        }
    }

    private void getData() {
        new HttpRequest<AppraisalOrderInfoResponse>()
                .with(this).setApiCode(ApiCst.getOtherorderDetail)
                .addParam("token", App.getToken(mContext))
                .addParam("order_id", orderId)
                .setListener(new HttpRequest.OnNetworkListener<AppraisalOrderInfoResponse>() {
                    @Override
                    public void onSuccess(AppraisalOrderInfoResponse response) {
                        model = response.model;
                        setView();
                    }

                    @Override
                    public void onFail(String message, AppraisalOrderInfoResponse response) {
                        toast(message);
                        finish();
                    }
                }).start(new AppraisalOrderInfoResponse());
    }


    /**
     * 确认收货
     */
    private void confirm() {
        ConfirmGoodsDialog confirmGoodsDialog = new ConfirmGoodsDialog(this);
        confirmGoodsDialog.setListener(new DialogEnterListener() {
            @Override
            public void cancel(Object tag) {

            }

            @Override
            public void enter(Object tag) {
                confirmOrCancel(40);
            }
        });
        confirmGoodsDialog.show();
    }

    /**
     * 确认收货或取消订单
     * 40-确认收货 90-取消订单
     *
     * @param status
     */
    public void confirmOrCancel(int status) {
        new HttpRequest<DefaultResponse>()
                .with(this).setApiCode(ApiCst.confirmOrCancelOtherorder)
                .addParam("token", App.getToken(mContext))
                .addParam("order_id", orderId)
                .addParam("status", status)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        toast(response.message);
                        getData();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                    }
                }).start(new DefaultResponse());

    }


    /**
     * 取消退款
     */
    public void cancelRefund() {
        new HttpRequest<DefaultResponse>()
                .with(this).setApiCode(ApiCst.cancelRefundOtherorder)
                .addParam("token", App.getToken(mContext))
                .addParam("refund_id", model.getRefund_id())
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        toast(response.message);
                        getData();
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        toast(message);
                    }
                }).start(new DefaultResponse());

    }

    private SellerAddressModel jijianModel;

    private void refreshSellerAddress() {
        new HttpRequest<SellerAddressResponse>()
                .with(this)
                .setApiCode(ApiCst.getSellerAddress)
                .addParam("key", style == 1 ? "jd" : "yh")//关键字 jd-鉴定 yh-养护 jm-寄卖 hs-回收 默认不传为jd
                .setListener(new HttpRequest.OnNetworkListener<SellerAddressResponse>() {
                    @Override
                    public void onSuccess(SellerAddressResponse response) {
                        jijianModel = response.getAddressModel();
                        setJijian();
                    }

                    @Override
                    public void onFail(String message, SellerAddressResponse response) {
                        toast(message);
                    }
                })
                .start(new SellerAddressResponse());
    }

    private void setJijian() {
        if (jijianModel == null) return;
        tvJijianName.setText(jijianModel.getUser());
        tvJijianPhone.setText(jijianModel.getTel());
        tvJijianAddress.setText(jijianModel.getAddress());
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    @Override
    public void onBackPressed() {
        if (backMain) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("intentToIndexFragment", true);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        } else
            super.onBackPressed();
    }


}
